package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;
//这里是全局异常处理中心
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
@ResponseBody
public class GlobalExceptionHandler {

    //自定义异常
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionCustomHandler(CustomException ce) {
        log.error(ce.getMessage());
        return R.error(ce.getMessage());
    }
    //拦截SQLIntegrityConstraintViolationException
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.error(ex.getMessage());
        //判断抛出的异常包不包含这句话 包含的话提示错误信息
        if (ex.getMessage().contains("Duplicate entry")) {
            //得到输入内中的部分内容
            String[] split = ex.getMessage().split(" ");
            //提示错误信息
            return R.error("输入的" + split[2] + "不允许有重复值");
        }
        //其他异常提示错误信息
        return R.error("未知错误");
    }
}
